package com.omg.api.handle;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.LoginArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.LoginBody;
import com.omg.api.result.header.LoginHeader;
import com.omg.constant.LPUtility;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPUser;
import com.omg.persistence.delegate.lifepoint.LPUserDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class LoginHandler extends Handler {

	private static final Logger LOG = Logger.getLogger(LoginHandler.class
			.getName());

	private static LoginHandler instance = null;

	static {
		instance = new LoginHandler();
	}

	public static LoginHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String email = ((LoginArgument) argument).getEmail();
		String passwd = ((LoginArgument) argument).getPasswd();

		LPUser lpUser = LPUserDelegate.getInstance().getLPUserByEmail(email);

		if (lpUser == null) {
			throw new Exception("" + ResponseCode.AP_E_Info_UserDoNotExist);
		}

		String passwd_local = lpUser.getPasswd();
		if (!passwd.equals(passwd_local)) {
			throw new Exception("" + ResponseCode.AP_E_Info_PasswordIsIncorrect);
		}

		// update sid
		String sid = LPUtility.getSid();
		lpUser.setSid(sid);
		LPUserDelegate.getInstance().updateLPUserSid(lpUser.getUserid(), sid);

		// login success!

		return getJson(lpUser);
	}

	private final String getJson(LPUser lpUser) throws Exception {
		try {
			// remove passwd
			lpUser.setPasswd(null);
			// remove version
			lpUser.setVersion(null);

			// construct result
			Result loginResult = new Result();

			// header
			LoginHeader header = new LoginHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			loginResult.setHeader(header);

			// body
			LoginBody body = new LoginBody();
			body.setUser(lpUser);
			loginResult.setBody(body);

			return new Gson().toJson(loginResult);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getMessage(), e);
			throw new Exception("" + ResponseCode.AP_E_Info_UnkownError);
		}
	}

}
